//
//  NSString+Category.m
//  FSProject
//
//  Created by 朱慕之 on 2018/12/13.
//  Copyright © 2018 zhumuzhi. All rights reserved.
//

#import "NSString+Category.h"
#import <CommonCrypto/CommonDigest.h>

#import "Reachability.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

//省份简称
#define kArrayProvinceShortName @[@"京",@"津",@"冀",@"晋",@"蒙",@"辽",@"吉",@"黑",@"沪",\
@"苏",@"浙",@"皖",@"闽",@"赣",@"鲁",@"豫",@"鄂",@"湘",\
@"粤",@"桂",@"琼",@"渝",@"川",@"贵",@"云",@"藏",@"陕",\
@"甘",@"青",@"宁",@"新"]


@implementation NSString (Category)


#pragma mark - 为空判断

+ (BOOL)isEmptyString:(NSString *)aStr {
    if (aStr==nil) {
        return YES;
    }
    if (!aStr) {
        return YES;
    }
    if ([aStr isEqual:[NSNull null]]) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (!aStr.length) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

- (void)isHaveEmptyString: (NSString *)string
                   result: (void(^)(bool isHave,NSRange range))result {
    NSRange range = [string rangeOfString:@" "];
    if (range.location != NSNotFound) {
        result (YES,range);
    } else {
        result (NO,NSMakeRange(0, 0));
    }
}


#pragma mark - 随机字符串

+ (NSString *)creatRandomStringWithCount: (NSInteger)count {
    
    NSMutableString *content = [NSMutableString string];
    
    for (NSInteger index = 0; index < count ; index++) {
        NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSInteger randomH = 0xA1 + arc4random()%(0xFE - 0xA1+1);
        NSInteger randomL = 0xB0 + arc4random()%(0xF7 - 0xB0+1);
        NSInteger number = (randomH<<8)+randomL;
        NSData *data = [NSData dataWithBytes:&number length:2];
        NSString *string = [[NSString alloc] initWithData:data encoding:gbkEncoding];
        [content appendString:string];
    }
    return content;
}

+ (NSInteger)creatRandomNumberWithCount: (NSInteger)count {
    NSInteger num = arc4random() % 2 + count * 10;
    return num;
}

+ (NSString *)creatRandomDateStringWithLength:(NSInteger)length {
    char data[length];
    
    for (NSInteger x=0;x < length;data[x++] = (char)('A' + (arc4random_uniform(26))));
    NSString *randomStr = [[NSString alloc] initWithBytes:data length:length encoding:NSUTF8StringEncoding];
    NSString *string = [NSString stringWithFormat:@"%@",randomStr];
    //    NSLog(@"获取随机字符串 %@",string);
    NSDate *date = [NSDate date];//这个是NSDate类型的日期，所要获取的年月日都放在这里；
    NSCalendar *cal = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;//这句是说你要获取日期的元素有哪些。获取年就要写NSYearCalendarUnit，获取小时就要写NSHourCalendarUnit，中间用|隔开；
    NSDateComponents *d = [cal components:unitFlags fromDate:date];//把要从date中获取的unitFlags标示的日期元素存放在NSDateComponents类型的d里面；
    //然后就可以从d中获取具体的年月日了；
    NSInteger year = [d year];
    NSInteger month = [d month];
    NSInteger day  =  [d day];
    NSInteger hour = [d hour];
    NSInteger minute = [d minute];
    NSInteger second = [d second];
    //    NSLog(@"year:%ld,month:%ld,day:%ld,hour:%ld,minute:%ld,second:%ld",(long)year,(long)month,(long)day,(long)hour,(long)minute,(long)second);
    NSString *stringCode = [NSString stringWithFormat:@"%@%@%@%@%@%@%@",string,@(year),@(month),@(day),@(hour),@(minute),@(second)];
    NSLog(@"%@",stringCode);
    return stringCode;
    
}


- (NSString *)unicodeString{
    NSString *tempStr1 = [self stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSPropertyListFormat format = NSPropertyListOpenStepFormat;
    NSString *returnStr = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:&format error:nil];
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

#pragma mark - 判断工具类

- (BOOL)isEmail
{
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:self];
}

- (BOOL)isPassword
{
    //提示 标签不能输入特殊字符
    NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:self]) {
        return YES;
    }
    return NO;
}

- (BOOL)isRealNumbers{
    NSString *regex = @"^(0|[1-9][0-9]*)$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:self];
}

- (BOOL)isMobileNumber{
    //    if (self.length != 11) {
    //        return NO;
    //    }
    //    /**
    //
    //     * 手机号码:
    //
    //     * 13[0-9], 14[5,7,9], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[1, 2, 3, 5, 6, 7, 8], 18[0-9], 170[0-9]
    //
    //     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159, 172,178,182,183,184,187,188,1705
    //
    //     * 联通号段: 130,131,132,155,156,185,186,145,171,175,176,1709
    //
    //     * 电信号段: 133,149,153,173,180,181,189,177,1700
    //
    //     */
    //
    //    NSString *MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|7[1-35-8]|8[0-9]|70)\\d{8}$";
    //
    //    /**
    //
    //     * 中国移动：China Mobile
    //
    //     *134,135,136,137,138,139,147,150,151,152,157,158,159, 172,178,182,183,184,187,188,1705
    //
    //     */
    //
    //    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[28]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    //
    //    /**
    //
    //     * 中国联通：China Unicom
    //
    //     * 130,131,132,155,156,185,186,145,171,175,176,1709
    //
    //     */
    //
    //    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[156]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    //
    //    /**
    //
    //     * 中国电信：China Telecom
    //
    //     *  133,149,153,173,180,181,189,177,1700
    //
    //     */
    //
    //    NSString *CT = @"(^1(33|49|53|7[37]|8[019])\\d{8}$)|(^1700\\d{7}$)";
    //
    //    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    //
    //    /**
    //
    //     * 大陆地区固话及小灵通
    //
    //     * 区号：010,020,021,022,023,024,025,027,028,029
    //
    //     * 号码：七位或八位
    //
    //     */
    //
    //    //  NSString * FT = @"^(0[0-9]{2})\\d{8}$|^(0[0-9]{3}(\\d{7,8}))$";
    //
    //    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    //
    //    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    //
    //    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    //
    //    if (([regextestmobile evaluateWithObject:self] == YES)
    //
    //        || ([regextestcm evaluateWithObject:self] == YES)
    //
    //        || ([regextestct evaluateWithObject:self] == YES)
    //
    //        || ([regextestcu evaluateWithObject:self] == YES)) {
    //
    //        return YES;
    //
    //    } else {
    //
    //        return NO;
    //
    //    }
    
    
    NSString *phone = @"^1\\d{10}$";
    NSPredicate *regextestPhone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phone];
    BOOL isPhone = [regextestPhone evaluateWithObject:self];
    return isPhone;
}


-(BOOL)isChinese{
    NSString *match=@"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@",match];
    return [predicate evaluateWithObject:self];
}

- (BOOL)isUrl
{
    NSString *regex =@"(http|https)://[^\\s]*";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)ifHasBlackSpace {
    if (!ValidStr(self)) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimedString = [self stringByTrimmingCharactersInSet:set];
    if ([trimedString length] == 0) {
        return YES;
    } else {
        return NO;
    }
}

- (BOOL)validateVinIsLegitimate{
    if (!ValidStr(self)) {
        return NO;
    }
    if (self.length != 17) {
        return NO;
    }
    NSMutableArray *vinArray = [NSMutableArray array];
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [vinArray addObject:substring];
    }];
    NSString *validateString = vinArray[8];
    //校验第9位是数字或X
    if (![validateString isRealNumbers] && ![validateString isEqualToString:@"X"]) {
        return NO;
    }
    NSArray *letterArray = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"J",@"K",@"L",@"M",@"N",@"P",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    //VIN每位字母对应的数值，数字就是本身
    NSArray *letterNoArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"1",@"2",@"3",@"4",@"5",@"7",@"9",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
    //VIN每一位对应的加权数
    NSArray *authorityNoArray = @[@"8",@"7",@"6",@"5",@"4",@"3",@"2",@"10",@"",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2"];
    
    NSMutableArray *vinCountArray = [NSMutableArray array];
    for (int i = 0; i < vinArray.count; i++) {
        NSString *str = vinArray[i];
        NSString *strCount = @"";
        for (int j = 0; j < letterArray.count; j++) {
            NSString *letter = letterArray[j];
            if ([str isEqualToString:letter]) {
                strCount = letterNoArray[j];
                break;
            }
            else{
                strCount = str;
            }
        }
        [vinCountArray addObject:strCount];
    }
    
    NSInteger product = 0;
    for (int m = 0; m < vinCountArray.count; m++) {
        if (m != 8) {
            NSString *count = vinCountArray[m];
            NSString *authorityNo = authorityNoArray[m];
            product = product + count.integerValue * authorityNo.integerValue;
        }
    }
    
    //将VIN中每一位字母或数字的对应数值乘以该位的加权系数，然后除以11，余数即为校验位，若余数为10，校验位为“X”
    NSInteger remainder = product % 11;
    if (remainder == 10) {
        if ([validateString isEqualToString:@"X"]) {
            return YES;
        }
        else{
            return NO;
        }
    }
    else{
        NSString *remainderString = [NSString stringWithFormat:@"%li",(long)remainder];
        if ([validateString isEqualToString:remainderString]) {
            return YES;
        }
        else{
            return NO;
        }
    }
}

- (BOOL)validateStringContainsEmoji{
    __block BOOL returnValue = NO;
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
     {
        const unichar hs = [substring characterAtIndex:0];
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    returnValue = YES;
                }
            }
        } else if (substring.length > 1) {
            const unichar ls = [substring characterAtIndex:1];
            if (ls == 0x20e3) {
                returnValue = YES;
            }
        } else {
            if (0x2100 <= hs && hs <= 0x27ff) {
                returnValue = YES;
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                returnValue = YES;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                returnValue = YES;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                returnValue = YES;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                returnValue = YES;
            }
        }
    }];
    return returnValue;
}


+ (BOOL)isNum:(NSString *)checkedNumString {
    checkedNumString = [checkedNumString stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(checkedNumString.length > 0) {
        return NO;
    }
    return YES;
}


- (BOOL)isContainSubString:(NSString *)subString{
    if([self rangeOfString:subString].location != NSNotFound){
        return YES;
    }else{
        return NO;
    }
}

+ (BOOL)validateCarNo:(NSString *)carNo
{
    if (!ValidStr(carNo)) {
        return NO;
    }
    if (carNo.length != 7) {
        return NO;
    }
    NSString *strFirstNameTemp = [carNo substringToIndex:1];
    if (![kArrayProvinceShortName containsObject:strFirstNameTemp]) {
        return NO;
    }
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-hj-np-zA-HJ-NP-Z]{1}[a-hj-np-zA-HJ-NP-Z_0-9]{4}[a-hj-np-zA-HJ-NP-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    return [carTest evaluateWithObject:carNo];
}

+ (BOOL)validateIdentityCard: (NSString *)identityCard
{
    NSString *regex = @"^(0|[1-9][0-9]*)$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:self];
}


#pragma mark - UIFont ToolMethod


+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize {
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize {
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil].size;
}

-(CGFloat)getSpaceLabelHeightwithSpeace:(CGFloat)lineSpace withFont:(UIFont*)font withWidth:(CGFloat)width
{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    //    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    /** 行高 */
    paraStyle.lineSpacing = lineSpace;
    // NSKernAttributeName字体间距
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@1.5f};
    CGSize size = [self boundingRectWithSize:CGSizeMake(width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}

+ (CGSize)sizeWithLabel:(UILabel *)label
{
    NSString *text = label.text;
    if (text == nil)
        text = @"字体";
    return [NSString sizeWithText:text andFont:label.font andMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
}

+ (CGSize)sizeWithText:(NSString *)text andFont:(UIFont *)font
{
    return [NSString sizeWithText:text andFont:font andMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
}

+ (CGSize)sizeWithText:(NSString *)text andFont:(UIFont *)font andMaxSize:(CGSize)maxSize
{
    CGSize expectedLabelSize = CGSizeZero;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    [paragraphStyle setLineSpacing:0];
    NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    
    expectedLabelSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
    
    return CGSizeMake(ceil(expectedLabelSize.width), ceil(expectedLabelSize.height));
}

#pragma mark - Time ToolMethod

+ (NSString *)getNowDateStringWithDateFormat:(NSString *)format
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = format;
    return [formatter stringFromDate:[NSDate date]];
}

+ (NSInteger)getNowYearOrMonth:(int)type
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth;
    NSDateComponents *component = [calendar components:unitFlags fromDate:[NSDate date]];
    if (type == 1)
        return component.year;
    else if (type == 2)
        return component.month;
    return 0;
}

+ (NSInteger)getMonthWithRegDate:(NSString *)regStr{
    
    NSString *regDateStr = regStr;
    if ([regStr rangeOfString:@"/"].location !=  NSNotFound) {
        regDateStr = [self replaceOldStr:@"/" withStr:@"-" withString:regStr];
        
    }
    else if ([regStr rangeOfString:@"年"].location != NSNotFound){
        regDateStr = [self replaceOldStr:@"年" withStr:@"-" withString:regStr];
        regDateStr = [self replaceOldStr:@"月" withStr:@"" withString:regDateStr];
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    NSDate *todayDate = [NSDate date];
    NSString *nowDate=[dateFormatter stringFromDate:todayDate];
    
    NSInteger nowYear = [[nowDate componentsSeparatedByString:@"-"].firstObject integerValue];
    NSInteger nowMonth = [[nowDate componentsSeparatedByString:@"-"].lastObject integerValue];
    
    NSArray *array = [regDateStr componentsSeparatedByString:@"-"];
    NSInteger regYear = 0;
    NSInteger regMonth = 0;
    NSInteger months = 0;
    if (array.count >= 2) {
        regYear = [[array firstObject] integerValue];
        regMonth = [[array objectAtIndex:1] integerValue];
        months = (nowYear - regYear) * 12;
        months += (nowMonth - regMonth);
    }else{
        return 0;
    }
    return months;
}

#pragma mark - 沙盒地址

+ (NSString *)getDocumentPath {
    return NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
}

+ (NSString *)getCachePath {
    return NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
}

+ (NSString *)getPreferencePath {
    return NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSUserDomainMask, YES).lastObject;
}

+ (NSString *)getTempPath {
    return NSTemporaryDirectory();
}

#pragma mark - 数字计算 ToolMethod

+ (NSString *)stringDisposeWithString:(NSString *)string rounding:(BOOL)round format:(NSString *)format
{
    if (round) {
        string = [[[self alloc] init] decimalwithFormat:format floatV:([string floatValue] + 0.001)];
    }
    
    NSInteger len = string.length;
    for (int i = 0; i < len; i++)
    {
        if (![string  hasSuffix:@"0"])
            break;
        else
            string = [string substringToIndex:[string length]-1];
    }
    if ([string hasSuffix:@"."])//避免像2.0000这样的被解析成2.
    {
        
        return [string substringToIndex:[string length]-1];//s.substring(0, len - i - 1);
    }
    else
    {
        return string;
    }
}

- (NSString *) decimalwithFormat:(NSString *)format  floatV:(float)floatV
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    
    [numberFormatter setPositiveFormat:format];
    
    return  [numberFormatter stringFromNumber:[NSNumber numberWithFloat:floatV]];
}

#pragma mark - 未分类 ToolMethod

+ (NSString *)replaceOldStr:(NSString *)stringToBeChanged withStr:(NSString *)stringToBeChangedWith withString:(NSString *)oldStr{
    NSString *newStr = [oldStr stringByReplacingOccurrencesOfString:stringToBeChanged withString:stringToBeChangedWith];
    return newStr;
}

+ (NSString *)jsonStringWithObject:(id)object
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if ([jsonData length] != 0 && error == nil)
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    else
        return nil;
}

- (NSString *)verticalString{
    NSMutableString * str = [[NSMutableString alloc] initWithString:self];
    if ([str containsString:@"-"]) {
        NSRange range = [str rangeOfString:@"-"];
        [str replaceCharactersInRange:range withString:@"|"];
    }
    NSInteger count = str.length;
    //针对特殊字符特殊处理
    NSArray *arraySpecial = @[@"45",@"VIN",@"vin"];
    for (NSString *strTemp in arraySpecial) {
        if ([str containsString:strTemp]) {
            NSRange range = [str rangeOfString:strTemp];
            NSMutableString *strLeft = [NSMutableString stringWithString:[str substringToIndex:range.location]];
            NSMutableString *strRight = [NSMutableString stringWithString:[str substringFromIndex:range.location+range.length]];
            
            count = strLeft.length;
            for (NSInteger i = 1; i < count; i ++) {
                [strLeft insertString:@"\n" atIndex:i*2 - 1];
            }
            count = strRight.length;
            for (NSInteger i = 1; i < count; i ++) {
                [strRight insertString:@"\n" atIndex:i*2 - 1];
            }
            
            NSMutableString *strMiddle = [NSMutableString stringWithString:strTemp];
            if (strLeft.length > 0) {
                [strMiddle insertString:@"\n" atIndex:0];
            }
            if (strRight.length > 0) {
                [strMiddle insertString:@"\n" atIndex:strMiddle.length];
            }
            
            str = [NSMutableString stringWithFormat:@"%@%@%@",strLeft,strMiddle,strRight];
            return  str;
        }
    }
    for (NSInteger i = 1; i < count; i ++) {
        [str insertString:@"\n" atIndex:i*2 - 1];
    }
    return str;
}

+ (NSString *)newNotNullStr:(NSString *)oldStr{
    if (oldStr) {
        return oldStr;
    }
    else{
        return @"";
    }
}

+ (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
    
    // 查找参数
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}


#pragma mark - 加密相关

#pragma mark Base64

- (NSString *)base64Encode
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

- (NSString *)base64Decode
{
    NSData *data = [[NSData alloc] initWithBase64EncodedString:self options:0];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

#pragma mark Hash Md5

- (NSString *)md5String
{
    const char *str = self.UTF8String;
    int length = (int)strlen(str);
    unsigned char bytes[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, length, bytes);
    
    return [self stringFromBytes:bytes length:CC_MD5_DIGEST_LENGTH];
}

- (NSString *)sha1String
{
    const char *str = self.UTF8String;
    int length = (int)strlen(str);
    unsigned char bytes[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(str, length, bytes);
    
    return [self stringFromBytes:bytes length:CC_SHA1_DIGEST_LENGTH];
}

- (NSString *)sha256String
{
    const char *str = self.UTF8String;
    int length = (int)strlen(str);
    unsigned char bytes[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(str, length, bytes);
    
    return [self stringFromBytes:bytes length:CC_SHA256_DIGEST_LENGTH];
}

- (NSString *)sha512String
{
    const char *str = self.UTF8String;
    int length = (int)strlen(str);
    unsigned char bytes[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512(str, length, bytes);
    
    return [self stringFromBytes:bytes length:CC_SHA512_DIGEST_LENGTH];
}

- (NSString *)stringFromBytes:(unsigned char *)bytes length:(int)length
{
    NSMutableString *strM = [NSMutableString string];
    
    for (int i = 0; i < length; i++) {
        [strM appendFormat:@"%02x", bytes[i]];
    }
    
    return [strM copy];
}

#pragma mark - 网络状态

+ (NSString *)networkStatus{
    Reachability *reachability   = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"WIFI";
    switch (internetStatus) {
        case ReachableViaWiFi:
            net = @"WIFI";
            break;
        case ReachableViaWWAN:
            net = [self getNetType];   //判断具体类型
            break;
        case NotReachable:
            net = @"当前无网路连接";
        default:
            break;
    }
    NSLog(@"net is %@", net);
    return net;
}

+ (NSString *)getNetType
{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    
    /// 注意：没有SIM卡，值为空
    NSString *currentStatus;
    
    NSString *currentNet = @"无网络";
    if (@available(iOS 12.1, *)) {
        if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
            NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
            if (radioDic.allKeys.count) {
                currentStatus = [radioDic objectForKey:radioDic.allKeys[0]];
            }
        }
    }else{
        NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
        currentStatus = [radioDic objectForKey:radioDic.allKeys[0]];
    }
    
    if ([currentStatus isEqualToString:CTRadioAccessTechnologyGPRS] || [currentStatus isEqualToString:CTRadioAccessTechnologyEdge]) {
        currentNet = @"2G";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyWCDMA] ||
              [currentStatus isEqualToString:CTRadioAccessTechnologyHSDPA] ||
              [currentStatus isEqualToString:CTRadioAccessTechnologyHSUPA] ||
              [currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] ||
              [currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] ||
              [currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] ||
              [currentStatus isEqualToString:CTRadioAccessTechnologyeHRPD]){
        currentNet = @"3G";
    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyLTE]){
        currentNet = @"4G";
    }else if (@available(iOS 14.1, *)) {
        if ([currentStatus isEqualToString:CTRadioAccessTechnologyNRNSA] ||
            [currentStatus isEqualToString:CTRadioAccessTechnologyNR]){
            currentNet = @"5G";
        }
    }
    return currentNet;
}



@end
